import java.awt.Color;
import java.awt.Image;
import java.awt.image.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import javax.imageio.ImageIO;

import java.awt.Point;

	   
public class ImageProcessing {
	BufferedImage image;
	Vector<Point> pixels;
	int level;
	static String path = "C:/Users/mengdi/Desktop/material/";
	
	/**constructor**/
	public ImageProcessing(int num){
		level = num;
	}
	
	public BufferedImage readImage() throws IOException{
		String filename = "floorplan_1_"+level;
		File file = new File(path+filename+".jpg"); 
		image = ImageIO.read(file);
		return image;
	}

    public Vector<Point> pixelSearch ( Color c, BufferedImage pic ){                
        int cVal = c.getRGB(); //get integer value of color we are trying to find

        int x1 = 0;
        int y1 = 0;
        int x2 = pic.getWidth();
        int y2 = pic.getHeight();
        
        pixels = new Vector<Point>();
      
        //next we iterate through all the possible coordinates to check each pixel
        for (int y = y1  ;y < y2 ; y ++) {
            for (int x = x1 ; x < x2 ; x++) {
                int color = pic.getRGB(x, y); //get the color of pixel at coords (xVal, yVal) 
                if (color == cVal) { //if the color is equal to the one we inputted to the function
                	Point point=new Point(x,y);
                    pixels.add(point);
                }
            }
        }
        return pixels;
    }
    public int[][] convertToMap() throws IOException{
    	BufferedImage pic = readImage();
    	int xsize = pic.getWidth();
        int ysize = pic.getHeight(); 
        int[][] available = new int[xsize][ysize];
        //next we iterate through all the possible coordinates to check each pixel
        for(int i=0;i<pixels.size();i++){
             int x = (int) pixels.get(i).x;
             int y = (int) pixels.get(i).y;
             available[x][y]=1;
        }
    	return available;
    }
    
    public void writeCSV() throws IOException{
    	File file = new File( "C:/Users/mengdi/Desktop/material/Statistics"+level+".csv");  
        if ( !file.exists() ) file.createNewFile();
	    FileWriter writer = new FileWriter(file);
	    int[][] map = convertToMap();
	    for(int i=0;i<map.length;i++){
	    	for(int j=0;j<map[0].length;j++){
	    		if(map[i][j]==1) writer.append(""+i+","+j+"\n");
	    	}
	    }
    	writer.flush();
    	writer.close();
    }
}


